<template>
    <!-- <h1>i m user</h1> -->
    <div class="manage">

        <!-- 新增弹窗 -->
        <el-dialog
        :title="dialogtitle"
        :visible.sync="dialogVisible" 
        :before-close="handleClose"
        width="50%">


        <el-form ref="form" :rules="rules" :model="form" label-width="80px" :inline="true" >
            <!-- prop属性用于与rules中的rule绑定 -->
            <el-form-item label="用户名" prop="userName">
                <el-input placeholder="请输入用户名" v-model="form.userName"></el-input>
            </el-form-item>
            <el-form-item label="入学年份" prop="inGrade">
                <el-input placeholder="请输入入学年份" v-model="form.inGrade"></el-input>
            </el-form-item>

            <el-form-item label="年级" prop="grade">
                <el-select v-model="form.grade" placeholder="请选择年级">
                    <el-option label="大一" value="大一"></el-option>
                    <el-option label="大二" value="大二"></el-option>
                    <el-option label="大三" value="大三"></el-option>
                    <el-option label="大四" value="大四"></el-option>
                    <el-option label="研一" value="研一"></el-option>
                    <el-option label="研二" value="研二"></el-option>
                    <el-option label="研三" value="研三"></el-option>
                    <el-option label="博士生" value="博士生"></el-option>
                    <el-option label="其他" value="其他"></el-option>
                </el-select>
            </el-form-item>



            <el-form-item label="学院" prop="college">
                <el-select v-model="form.college" placeholder="请选择学院">
                    <el-option label="信息与通信工程学院" value="信息与通信工程学院"></el-option>
                    <el-option label="电子工程学院" value="电子工程学院"></el-option>
                    <el-option label="计算机学院（国家示范性软件学院）" value="计算机学院（国家示范性软件学院）"></el-option>
                    <el-option label="网络空间安全学院" value="网络空间安全学院"></el-option>
                    <el-option label="人工智能学院" value="人工智能学院"></el-option>
                    <el-option label="现代邮政学院（自动化学院）" value="现代邮政学院（自动化学院）"></el-option>
                    <el-option label="集成电路学院" value="集成电路学院"></el-option>
                    <el-option label="经济管理学院" value="经济管理学院"></el-option>
                    <el-option label="人文学院" value="人文学院"></el-option>
                    <el-option label="国际学院" value="国际学院"></el-option>
                    <el-option label="马克思主义学院" value="马克思主义学院"></el-option>
                    <el-option label="网络教育学院（继续教育学院）" value="网络教育学院（继续教育学院）"></el-option>
                    <el-option label="理学院" value="理学院"></el-option>
                    <el-option label="数字媒体与设计艺术学院" value="数字媒体与设计艺术学院"></el-option>
                    <el-option label="应急管理学院" value="应急管理学院"></el-option>
                    <el-option label="体育部" value="体育部"></el-option>
                    <el-option label="其他" value="其他"></el-option>
                </el-select>
            </el-form-item>

            <el-form-item label="身份" prop="identity">
                <el-select v-model="form.identity" placeholder="请选择身份">
                    <el-option label="北邮人" value="北邮人"></el-option>
                    <el-option label="游客" value="游客"></el-option>
                </el-select>
            </el-form-item>

            <el-form-item label="专业" prop="major">
                <el-input placeholder="请输入专业" v-model="form.major"></el-input>
            </el-form-item>

            <el-form-item label="积分" prop="points">
                <el-input placeholder="请输入积分" v-model="form.points"></el-input>
            </el-form-item>
        </el-form>
            
        <span slot="footer" class="dialog-footer">
            <el-button @click="cancel">取 消</el-button>
            <el-button type="primary" @click="submit">确 定</el-button>
        </span>
        </el-dialog>

        <!-- +新增按钮 -->
        <div class="manage-header">
            <el-button @click="handleAdd" type="primary">
                + 新增
            </el-button>
            <!-- 搜索表单 -->
            <el-form>

            </el-form>
        </div>
<!-- 
        <div class="manage-header">
            <el-button @click="fetchRealData" type="primary">
                + CHA
            </el-button>
        </div> -->

        <div class="common-table">
            <el-table
            height="90%"
            :data="tableData"
            stripe
            :row-style="{height: '100px'}"
            style="width: 100%">
                <el-table-column
                    prop="userId"
                    label="用户ID">
                </el-table-column>
                <el-table-column
                    prop="userName"
                    label="用户名">
                </el-table-column>
                <el-table-column
                    prop="inGrade"
                    label="入学年份">
                </el-table-column>
                <el-table-column
                    prop="grade"
                    label="年级">
                </el-table-column>
                <el-table-column
                    prop="college"
                    label="学院">
                </el-table-column>
                <el-table-column
                    prop="major"
                    label="专业">
                </el-table-column>
                <el-table-column
                    prop="identity"
                    label="身份">
                </el-table-column>
                <el-table-column
                    prop="points"
                    label="积分">
                </el-table-column>
                <el-table-column
                    prop="operation"
                    label="操作"
                    min-width="100px">
                    <template slot-scope="scope">
                            <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
                            <el-button type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <div class="pager">
                <el-pagination
                    layout="prev, pager, next"
                    :total="this.total"
                    @current-change="handlePage">
                </el-pagination>
            </div>
        </div>


    </div>
</template>

<script>
import {getRealUser,addRealUser,deleteRealUser,updateRealUser} from "../api"

export default{
    name:'PageOne',
    data(){
        return{
            count : 1,
            dialogVisible:false,
            dialogtitle:"新增用户",
            //tableData中总条数
            total:0,
            pageData:{
                pageSize: 10,
                currentPage : 1
            },
            tempObj:'',
            //空form解决回显bug
            empty_form:{
                userName:'',
                inGrade:'',
                grade:'',
                college:'',
                major:'',
                identity:'',
                points:'',
            },
            // 需要显示的数据
            form:{
                userName:'',
                inGrade:'',
                grade:'',
                college:'',
                major:'',
                identity:'',
                points:'',


            },
            rules:{
                userName:[
                    {required:true , message:'请输入用户名'}
                ],
                inGrade:[
                    {required:true , message:'请输入入学年份'}
                ],             
                grade:[
                    {required:true , message:'请选择年级'}
                ],
                college:[
                    {required:true , message:'请选择学院'}
                ],
                major:[
                    {required:true , message:'请输入专业'}
                ],
                identity:[
                    {required:true , message:'请选择身份'}
                ],
                points:[
                    {required:true , message:'请输入积分'}
                ],
            },
             tableData:[
 
        ],
            modaltype:0//0新增，1编辑，标记弹窗状态
        }
    },
    methods:{
        submit(){
            this.$refs.form.validate((valid) => {
                //如果数据不完整，valid为false
                if(valid){
                    console.log("表单提交的数据为",this.form);
                    //!!!此处浏览器中打印出为空，但实际上可以向后端提交数据，原因未知
                    //this.from是data,this.$refs.form是真正的表单
                    
                    if(this.modaltype === 0){//新增的表单
                    //    //对后端发送增加请求......
                        addRealUser(this.form).then((data)=>{
                            console.log("新增表单返回数据",data)
// data：{
//     "data": {
//         "code": 200,
//         "flag": true,
//         "data": 1
//     },
//     "status": 200,
//     "statusText": "",
//     "headers": {
//         "content-type": "application/json"
//     },
//     "config": {xxx}
//}                      

                            if(data.data.code == 200){
                                console.log("新增请求成功")
                                this.$message({
                                    type: 'success',
                                    message: '添加成功!'
                                });
                                //重新调用获取数据接口
                                this.fetchRealData()
                            }else{
                                console.log("新增请求失败")
                            }
                        })
                    }else{//修改的表单

                        // // 对后端修改增加请求......
                        //tempObj比form多一个userId，并且将form修改后的数据覆盖自身
                        this.tempObj={...this.tempObj,...this.form}
                        updateRealUser(this.tempObj).then((ret) =>{
                            console.log("更新返回的数据",ret)
// ret：{
//     "data": {
//         "code": 200,
//         "flag": true,
//         "data": 1
//     },
//     "status": 200,
//     "statusText": "",
//     "headers": {
//         "content-type": "application/json"
//     },
//     "config": {xxx}
//}                      



                            if(ret.data.code == 200){
                                console.log("更新成功")
                                this.$message({
                                    type: 'success',
                                    message: '更新成功!'
                                });
                                //重新渲染
                                this.fetchRealData()
                            }else{
                                this.$message({
                                type: 'info',
                                message: '未知原因更新失败，响应代码不为200'
                                });
                            }
                            // this.form = this.empty_form
                        })
                    }
                    // this.handleClose()
                    this.handleClose()
                }
                else{
                    //do nothing
                }
            })
        },
        handleClose(){
            this.$refs.form.resetFields()
            console.log("关闭弹窗，reset success")
            console.log("关闭后表单",this.form)
            this.dialogVisible = false
            // this.form.user_name=''
        },
        cancel(){
            this.handleClose()
        },
        handleEdit(row){
            console.log("当前准备进行修改的行数据",row)

            //先修改弹窗的模式与标题，再显示弹窗
            this.modaltype = 1
            this.dialogtitle = " 修改用户信息"
            this.dialogVisible = true

            //不能直接赋值，不然直接修改了数据，需要点击确认才能修改
            //利用obj存储row中冗余的id项以及其余可能项，并传入obj的row进行修改
            //不使用this.obj =  row是因为这样两个变量会指向同一块地址，实际上是同一个变量的两个引用
            this.tempObj = JSON.parse(JSON.stringify(row));
            //form只存对应表单项内的数据
            // form:{
            //     userName:'',
            //     inGrade:'',
            //     grade:'',
            //     college:'',
            //     major:'',
            //     identity:'',
            //     points:'',
            this.form = {
                    userName: this.tempObj.userName,
                    inGrade: this.tempObj.inGrade,
                    grade: this.tempObj.grade,
                    college: this.tempObj.college,
                    major: this.tempObj.major,
                    identity: this.tempObj.identity,
                    points: this.tempObj.points
                    };
            // this.form.user_name = this.obj.user_name
            // this.form.grade = this.obj.grade
            // this.form.college_name = this.obj.college_name
            // this.form.entry_year = this.obj.entry_year
            // this.form.major = this.obj.major
            // this.form.points = this.obj.points

            console.log('回显表单form',this.form)
            // console.log('obj',this.obj)

        },
        handleDelete(row){
            console.log("deleteRowId",row.userId)
            this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
            }).then(() => {//用户点击了确认按钮
                deleteRealUser(row.userId).then((ret)=>{
                    console.log("删除返回的数据",ret)
// ret:
// {"data": {
//         "code": 200,
//         "flag": true,
//         "data": 1
//          },
//  "status": 200,
//  "statusText": "",
//  "headers": {
//      "content-type": "application/json"
//          },
//     "config": {
//        xxx
//         },
                    if(ret.data.code == 200){
                        this.$message({
                        type: 'success',
                        message: '删除成功!'
                        });
                        //重新获取数据
                        // console.log(this.tableData)
                        this.fetchRealData()
                        // console.log(this.tableData)
                    }else{
                        this.$message({
                        type: 'info',
                        message: '未知原因删除失败，响应代码不为200'
                });       
                    }
                })
            }).catch(() => {//用户点击了取消按钮
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });          
            });
        },
        handleAdd(){
            //显示调用去掉bug
            // this.handleClose()
            //修改弹窗状态
            this.modaltype = 0//新增
            this.dialogtitle = "新增用户"
            //显示弹窗
            this.dialogVisible = true
        },
        handlePage(currentPage){
            console.log(currentPage)
            this.pageData.currentPage = currentPage
            this.fetchRealData()
        },
        // fetchData() {
        // //     getUser().then(({ data }) => {
        // //     this.tableData = data; // 更新表格数据
        // //     this.total = this.tableData.length
        // //     // console.log("fetchData",this.tableData)
        // // })
        // },


        //获取数据
        fetchRealData(){
            getRealUser(this.pageData.pageSize,this.pageData.currentPage).then(({data}) => {
                console.log("请求获取到的分页数据",data)
//data: {
//         "code": 200,
//         "flag": true,
//         "data": {
//             "currentPage": 1,
//             "pageSize": 10,
//             "total": 52,
//             "data": [
//                 {xxxxxx}
//             ]
//      }
                if(data.code == 200){
                    this.tableData = data.data.data; // 更新表格数据
                    this.total = data.data.total;
                    console.log('tableData',this.tableData)
                }
                else{
                    this.$message({
                    type: 'info',
                    message: '未知原因获取分页数据失败，代码不为200'
                    });       
                    console.log("code is not 200")
                }
            })
        }
    },    
    mounted(){
        // this.fetchData();
        this.fetchRealData();
    }
}
</script>

<style lang="less">
.manage{
    height: 100%;
    .common-table{
        position: relative;
        height: calc(100% - 62px);
        .pager{
        position: absolute;
        bottom: 0;
        right: 20px;
        }
    }
}
</style>